package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("validators.UsernameValidator")
public class UsernameValidator implements Validator {

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());
	
	private Pattern pattern;
	private Matcher matcher;

	private static final String USERNAME_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*."
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)$";

	public UsernameValidator() {
		pattern = Pattern.compile(USERNAME_PATTERN);
	}
	
	
	/**
	 * @author Katona Gabor
	 * @version 1.0
	 * @param FacesContext
	 *            context, UIComponent component, Verifies if the username respects the pattern
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		// TODO Auto-generated method stub
		String newUsername = (String) value;
		
			if (newUsername.length() < 4) {
				FacesMessage fMessage = new FacesMessage(
						bundle.getString("Validators_UsernameValidator_Error1"));
				throw new ValidatorException(fMessage);
			}

			matcher = pattern.matcher((CharSequence) value);
		if (!matcher.matches()) {
			FacesMessage message = new FacesMessage(bundle.getString("Validators_UsernameValidator_Error2"));
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}

	}
}
